<?php

namespace app\api\model;


use think\Exception;
use think\Model;

class WorkProcess extends Model
{
    protected $table = 'work_process';
    protected $connection = 'database.zong';
    protected $resultSetType = 'collection';
    
    /*
     * 获取模版数据
     */
    public function WorkTemplate($id)
    {
        $list = $this->field('work_process.title,work_type.title as workTypeTitle,work_type.id as workTypeId,work_process.id,work_process.sort as workSort,work_type.sort AS workTypeSort,work_template_info.start_day,work_template_info.end_day,work_process.important')
            ->Join('work_template_info', 'work_template_info.work_process_id=work_process.id', 'left')
            ->Join('work_template_detailed', 'work_template_detailed.work_template_id=work_template_info.work_template_id', 'left')
            ->Join('work_template', 'work_template_info.work_template_id=work_template.id', 'right')
            ->Join('work_type', 'work_type.id=work_process.work_type', 'left')
            ->where('work_template.id', $id)
            ->where('work_template.status', 1)
            ->where('work_process.status', 1)
            ->group('work_template_info.work_process_id')
            ->select();
        return $list;
    }
    
    /*
    * 根据清单获取数据
    */
    public function WorkDetailed($id)
    {
        $list = $this->field('work_process.title,work_type.title as workTypeTitle,work_type.id as workTypeId,work_process.id,work_process.sort as workSort,work_type.sort AS workTypeSort,work_template_info.start_day,work_template_info.end_day')
            ->Join('work_template_info', 'work_template_info.work_process_id=work_process.id', 'left')
            ->Join('work_template_detailed', 'work_template_detailed.work_template_id=work_template_info.work_template_id', 'left')
            ->Join('work_template', 'work_template_info.work_template_id=work_template.id', 'right')
            ->Join('work_type', 'work_type.id=work_process.work_type', 'left')
            ->where('work_template.id', $id)
            ->where('work_template.status', 1)
            ->where('work_process.status', 1)
            ->group('work_template_info.work_process_id')
            ->select();
        
        return $list;
    }
    
    /*
     * 获取清单模版数据
     */
    public function WorkTemplateDetailed($id)
    {
        $list = $this->field('work_process.title,work_type.title as workTypeTitle,work_type.id as workTypeId,work_process.id,work_process.sort as workSort,work_type.sort AS workTypeSort,work_process.important')
            ->Join('work_type', 'work_type.id=work_process.work_type', 'left')
            ->whereIn('work_process.id', $id)
            ->where('work_process.status', 1)
            ->select();
        
        return $list;
    }
    
    /*
     * 根据工种获取工序
     */
    public function WorkTypeAcquisitionProcess($id)
    {
        $result = $this->field('work_process.*,work_template_info.start_day,start_day,work_template_info.end_day')
            ->join('work_template_info', 'work_process.id=work_template_info.work_process_id and  work_template_info.work_type_id=' . $id . '', 'left')
            ->where('work_process.work_type', $id)
            ->where('status', 1)
            ->select();
        return $result;
    }
    
    /*
     * 根据工种获取清单
     */
    public function JobAcquisitionList($id)
    {
        $result = $this->field('work_process.*,work_template_info.start_day,start_day,work_template_info.end_day')
            ->where('work_process.work_type', $id)
            ->where('status', 1)
            ->column('id');
        return $result;
    }
    
    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys 要排序的键字段
     * @param string $sort 排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    public static function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
    
    public function saveList($list, $orderId,$who=1,$userId=0)
    {
        db()->startTrans();
        try {
            foreach ($list as $p => $item) {
                if (!empty($item['list'])) {
                    foreach ($item['list'] as $k => $value) {
                        if (empty($value['data'])) {
                            unset($list[$p]['list'][$k]);
                        }
                    }
                } else {
                    unset($list[$p]);
                }
                
            }
            foreach ($list as $p => $item) {
                $list[$p]['list'] = array_merge($item['list']);
            }
            $workCapitalTypeListId = \db('work_capital_type')->where(['order_id' => $orderId, 'agent' => 0])->column('id');
            \db('work_capital_procedure')->whereIn('work_capital_type_id', $workCapitalTypeListId)->update(['deleted_at' => time()]);
            $working_procedure_id = \db('work_capital_procedure')->where('deleted_at', "<>", 0)->column('working_procedure_id');
            if(!empty($list) && !empty($working_procedure_id)){
                \db('order_production')->where('delete_time', 0)->where('order_id', $orderId)->whereIn('working_procedure_id', $working_procedure_id)->update(['delete_time' => time(), 'update_time' => time()]);
            }
            
            foreach ($list as $item) {
                if (!empty($item['list'])) {
                    $workCapitalTypeList   = \db('work_capital_type')->where(['type_work' => $item['typeWork'], 'type_work_id' => $item['typeWorkId'], 'order_id' => $orderId])->find();
                    $workCapitalTypeListId = \db('work_capital_type')->where(['order_id' => $orderId, 'agent' => 0])->column('id');
                    if ($workCapitalTypeList) {
                        \db('work_capital_type')->where(['type_work' => $item['typeWork'], 'type_work_id' => $item['typeWorkId'], 'order_id' => $orderId])->update(['type_sort' => $item['workTypeSort']]);
                        $workCapitalTypeId = $workCapitalTypeList['id'];
                    } else {
                        $workCapitalTypeId = \db('work_capital_type')->insertGetId(['type_work' => $item['typeWork'], 'type_work_id' => $item['typeWorkId'], 'type_sort' => $item['workTypeSort'], 'order_id' => $orderId, 'work_template_id' => isset($item['workTemplateId'])?$item['workTemplateId']:0]);
                    }
                    foreach ($item['list'] as $k => $value) {
                        if ($value['workTypeSaveId'] != 0) {
                            \db('work_capital_procedure')->where('id', $value['workTypeSaveId'])->update([
                                'working_sort' => $value['sort'],
                                'working_start' => !empty($value['working_start']) ? strtotime($value['working_start'] . " 00:00:00") : 0,
                                'working_end' => !empty($value['working_start']) ? strtotime($value['working_end'] . " 23:59:59") : 0,
                                'deleted_at' => 0,
                            ]);
                            $workCapitalProcedureId = $value['workTypeSaveId'];
                        } else {
                            $workCapitalProcedureId = \db('work_capital_procedure')->insertGetId([
                                'work_capital_type_id' => $workCapitalTypeId,
                                'working_procedure' => $value['workingProcedure'],
                                'working_procedure_id' => $value['workingProcedureId'],
                                'working_sort' => $value['sort'],
                                'working_start' => strtotime($value['working_start']),
                                'working_end' => strtotime($value['working_end']),
                                'images' => '',
                            ]);
                        }
                        $type=1;
                        foreach ($value['data'] as $val) {
                            if (isset($val['workCapitalRelationSaveId']) && $val['workCapitalRelationSaveId'] != 0) {
                                \db('work_capital_relation')->where('id', $val['workCapitalRelationSaveId'])->update([
                                    'update_date' => time(),
                                ]);
                                
                            } else {
                                \db('work_capital_relation')->insert([
                                    'work_capital_procedure_id' => $workCapitalProcedureId,
                                    'capital_id' => $val['capital_id'],
                                    'type' => isset($val['type']) ? $val['type'] : 1,
                                    'creation_time' => time(),
                                ]);
                                
                            }
                            $type=isset($val['type']) ? $val['type'] : 1;
                        }
                        
                        $working_start        = !empty($value['working_start']) ? strtotime($value['working_start'] . " 00:00:00") : 0;
                        $working_end          = !empty($value['working_start']) ? strtotime($value['working_end'] . " 23:59:59") : 0;
                        $working_procedure_id = $value['workingProcedureId'];
                        $order_id             = $orderId;
                        $capital_id           = implode(',', array_column($value['data'], 'capital_id'));
                        $order_production     = db('order_production')->where('order_id', $orderId)->where('working_procedure_id', $value['workingProcedureId'])->find();
                        if ($order_production) {
                            db('order_production')->where('order_id', $orderId)->where('working_procedure_id', $value['workingProcedureId'])->update(['working_start' => $working_start, 'working_end' => $working_end, 'capital_id' => $capital_id,'update_time' => time(), 'working_sort' => $value['sort'], 'delete_time' => 0]);
                        } else {
                            db('order_production')->insert(['working_start' => $working_start, 'working_end' => $working_end, 'working_procedure_id' => $working_procedure_id, 'creation_time' => time(), 'order_id' => $order_id,'type' =>$type, 'capital_id' => $capital_id,'user_type'=>$who,'user_id'=>$userId, 'working_sort' => $value['sort']]);
                        }
                        
                        
                    }
                }
                
            }
            db()->commit();
            return ['code' => 200, 'message' => '成功'];
        } catch (Exception $e) {
            db()->rollback();
            return ['code' => 300, 'message' => $e->getMessage()];
            
        }
    }
    
    
}
